package com.windoent.yugioh.ui.fragment.saishi.ongoing;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.SaiShiOnGoingCaipanAuthAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.OnGingShenHeData;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.saishi.PanFaDetailsActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.dialog.AuthSubmitGradeShenHeDialog;
import com.windoent.yugioh.widget.dialog.PanFaUserDetailsDialog;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/21 10:47
 * desc   :裁判审核
 */
public class OnGoingShenHeFragment extends BaseFragment {
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private SaiShiOnGoingCaipanAuthAdapter adapter;
    private String statusid = "";

    public static OnGoingShenHeFragment newsInstance(String id) {
        //创建 Bundle
        OnGoingShenHeFragment fragment = new OnGoingShenHeFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_ongoing_shenhe;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
    }

    private void initData() {
        initAdapter();
    }

    private void initView() {
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
    }

    private void initRefreshData(String id) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(id);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore(id);
            }
        });
    }

    private void loadMore(String id) {
        mCount = mCount + 1;
        getJudgeAuthPlayersList(id, mCount + "", limit, false);
    }

    private void fresh(String id) {
        getGameStatusRole(id);
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        showLoadingDialog("");
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid == 8) {
                                        //发送eventbus粘性事件
                                        FragmentActivityMessageEvent event = new FragmentActivityMessageEvent();
                                        event.setMessage(1);
                                        event.setRole(role);
                                        event.setStatusId(statusid);
                                        EventBus.getDefault().postSticky(event);
                                    } else if (statusid != 2 && statusid != 8) {
                                        mCount = 1;
                                        getJudgeAuthPlayersList(id, mCount + "", limit, true);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SaiShiOnGoingCaipanAuthAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty_duizhen, mRecyclerView, false));
        adapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(adapter);
        adapter.addChildClickViewIds(R.id.btn_get_code, R.id.rl_left, R.id.rl_right);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<OnGingShenHeData.DataBean.ResBean> data = adapter.getData();
                OnGingShenHeData.DataBean.ResBean resBean = data.get(position);
                if (resBean != null) {
                    int verify_status_id = resBean.getVerify_status_id();//"1": "提交中","2": "提交失败","3": "审核","4": "成绩审核有效，不显示按钮"
                    switch (view.getId()) {
                        case R.id.btn_get_code:
                            int vid = resBean.getId();
                            if (verify_status_id == 3) {
                                showSureGradeCorrectDialog(vid + "", resBean.getDesk_name());
                            } else if (verify_status_id == 1 || verify_status_id == 2) {
                                showSureModifyDialog(resBean, vid + "", BaseMethod.notNull(statusid) && statusid.equals("5"));
                            }
                            break;
                        case R.id.rl_left:
                            getPanFaStyleList(resBean.getA_nickname(), id, resBean.getA_id() + "", resBean.getId() + "");
                            break;
                        case R.id.rl_right:
                            getPanFaStyleList(resBean.getB_nickname(), id, resBean.getB_id() + "", resBean.getId() + "");
                            break;
                    }
                }
            }
        });
    }

    //判罚类型列表
    private void getPanFaStyleList(String name, String gameId, String userId, String vid) {
        PhoneLive.getPanFaStyleList(getUserToken(), gameId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            showUserPanFaDialog(name, gameId, userId, response, vid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getContext().getString(R.string.string_response_error));
                }
            }
        });
    }

    //用户对阵判罚记录
    private void showUserPanFaDialog(String name, String gameId, String userId, String response, String vId) {
        PanFaUserDetailsDialog dialog = new PanFaUserDetailsDialog(mContext);
        dialog.setUserStr(name, gameId, userId, response);
        dialog.setOnclickListener(new PanFaUserDetailsDialog.onClickListener() {
            @Override
            public void onClickSure(String type_id, String remark) {
                panfaPlayers(vId, userId, type_id, remark);
            }

            @Override
            public void clickMore() {
                Intent intent = new Intent(mContext, PanFaDetailsActivity.class);
                intent.putExtra("gameId", gameId);
                intent.putExtra("userId", userId);
                mContext.startActivity(intent);
            }
        });
        dialog.show();
    }

    //判罚操作
    private void panfaPlayers(String vid, String userId, String type_id, String remark) {
        PhoneLive.panfaPlayers(getUserToken(), vid, userId, type_id, remark, statusid, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, mContext.getString(R.string.string_panfa_player_sucess)), null);
                        } else {
                            BaseMethod.showFailDialog(mContext, mContext.getString(R.string.string_panfa_player_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(mContext.getString(R.string.string_response_error));
                }
            }
        });
    }

    //确认成绩有效
    private void showSureGradeCorrectDialog(String id, String deskName) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_sure_grade_correct_warn));
        dialog.setTitle(deskName);
        dialog.setYesStr(getString(R.string.string_valid));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                //确认成绩有效
                judgeAuthValid(id);
            }
        });
        dialog.show();
    }

    //修改成绩
    private void showSureModifyDialog(OnGingShenHeData.DataBean.ResBean resBean, String vid, boolean outGame) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setTvContent(getString(R.string.string_sure_modify_grade_warn));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                showAuthDialog(resBean, vid, outGame);
            }
        });
        dialog.show();
    }

    //确认成绩有效
    private void judgeAuthValid(String vid) {
        showLoadingDialog("");
        PhoneLive.judgeAuthValid(getUserToken(), vid, statusid, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_sppaly_judge_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    fresh(id);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_sppaly_judge_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //裁判审核成绩
    private void showAuthDialog(OnGingShenHeData.DataBean.ResBean resBean, String vid, boolean outGame) {
        AuthSubmitGradeShenHeDialog dialog = new AuthSubmitGradeShenHeDialog(mContext);
        dialog.setInfo(resBean, id, outGame, statusid);
        dialog.setOnclickListener(new AuthSubmitGradeShenHeDialog.onClickListener() {
            @Override
            public void onClick(int selectPosition) {//1左胜利，2右胜，3平,4双败
                judgeEditGrade(selectPosition + "", vid);
            }
        });
        dialog.show();
    }

    //裁判修改成绩
    private void judgeEditGrade(String grade, String vid) {
        showLoadingDialog("");
        PhoneLive.judgeEditGrade(getUserToken(), vid, grade, statusid, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    GeneralBean fromJson = gson.fromJson(response, GeneralBean.class);
                    if (fromJson != null) {
                        int code = fromJson.getCode();
                        String msg = fromJson.getMsg();
                        if (code == 200) {
                            BaseMethod.showSucessDialog(mContext, BaseMethod.notNullDefaultValue(msg, getString(R.string.string_refree_modify_grade_sucess)), new SucessFailAutoDismissDialog.OnInterface() {
                                @Override
                                public void onDissmiss() {
                                    fresh(id);
                                }
                            });
                        } else {
                            BaseMethod.showFailDialog(mContext, getString(R.string.string_refree_modify_grade_fail), BaseMethod.notNullDefaultValueNull(msg));
                        }
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //审核选手成绩列表
    private void getJudgeAuthPlayersList(String id, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getJudgeAuthPlayersList(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            OnGingShenHeData json = gson.fromJson(response, OnGingShenHeData.class);
                            if (json != null) {
                                OnGingShenHeData.DataBean data = json.getData();
                                if (data != null) {
                                    statusid = data.getStatusid();
                                    List<OnGingShenHeData.DataBean.ResBean> res = data.getRes();
                                    if (res != null) {
                                        if (fresh) {
                                            mSmartLayout.finishRefresh(true);
                                            adapter.setNewInstance(res);
                                        } else {
                                            mSmartLayout.finishLoadMore(true);
                                            adapter.addData(res);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事进行中审核tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事进行中审核tab");
        }
        getDetailsId();
    }

    private String id = "";

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            initRefreshData(id);
            fresh(id);
        }
    }
}
